package com.example.icongyou;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.icongyou.adapter.AssignmentAdapter;
import com.example.icongyou.api.CourseApi;

import com.example.icongyou.api.TeamAssignmentApi;
import com.example.icongyou.bean.AssignmentDisplay;
import com.example.icongyou.bean.Course;
import com.example.icongyou.bean.TeamAssignment;
import com.example.icongyou.retrofit.RetrofitClient;
import com.example.icongyou.utils.SessionManager;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AssignmentListActivity extends AppCompatActivity {

    private static final String TAG = "AssignmentListActivity";

    private RecyclerView recyclerView;
    private AssignmentAdapter adapter;
    private TextView tvCourseTitle;
    private TextView tvCourseDescription;
    private TextView tvMainTitle;

    private SessionManager sessionManager;
    private String currentTeacherId;
    private Course currentCourse;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_assigment_list);

        // 初始化会话管理
        sessionManager = new SessionManager(this);
        currentTeacherId = sessionManager.getTeacherId();

        // 初始化视图
        initViews();

        // 加载课程数据
        loadCourseData();
    }

    private void initViews() {
        tvMainTitle = findViewById(R.id.tv_main_title);
        tvCourseTitle = findViewById(R.id.tv_course_title);
        tvCourseDescription = findViewById(R.id.tv_course_description);

        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

      adapter = new AssignmentAdapter(new ArrayList<>(), this::onAssignmentItemClick);
        recyclerView.setAdapter(adapter);

        // 设置默认值
        tvMainTitle.setText("项目实践");
        tvCourseTitle.setText("课程需求");
        tvCourseDescription.setText("python");
    }

    private void loadCourseData() {
        // 1. 获取 CourseApi 实例
        CourseApi api = RetrofitClient.getCourseApi();

        // 2. 将teacherId转换为Integer
        try {
            Integer teacherIdInt = Integer.parseInt(currentTeacherId);

            // 3. 调用 API 查询教师课程信息
            Call<List<Course>> call = api.getCoursesByTeacherId(teacherIdInt);

            call.enqueue(new Callback<List<Course>>() {
                @Override
                public void onResponse(Call<List<Course>> call, Response<List<Course>> response) {
                    if (response.isSuccessful() && response.body() != null && !response.body().isEmpty()) {
                        List<Course> courses = response.body();
                        // 取第一个课程显示
                        currentCourse = courses.get(0);
                        updateCourseUI(currentCourse);

                        // 获取到课程信息后加载作业数据
                        loadAssignmentData();

                        Log.d(TAG, "成功获取课程信息: " + currentCourse.getCourseName());

                    } else if (response.code() == 404) {
                        // 404 表示未找到课程
                        showDefaultCourseInfo();
                        Toast.makeText(AssignmentListActivity.this, "该教师暂无课程", Toast.LENGTH_SHORT).show();
                    } else {
                        // 其他 API 错误
                        showDefaultCourseInfo();
                        String errorMsg = "获取课程信息失败: 错误码 " + response.code();
                        Toast.makeText(AssignmentListActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                        Log.w(TAG, "获取课程信息失败，状态码: " + response.code());
                    }
                }

                @Override
                public void onFailure(Call<List<Course>> call, Throwable t) {
                    showDefaultCourseInfo();
                    // 网络或连接错误
                    Toast.makeText(AssignmentListActivity.this, "获取课程信息失败：" + t.getMessage(), Toast.LENGTH_LONG).show();
                    Log.e(TAG, "获取课程信息网络错误: " + t.getMessage());
                }
            });

        } catch (NumberFormatException e) {
            showDefaultCourseInfo();
            Toast.makeText(this, "教师ID格式错误", Toast.LENGTH_SHORT).show();
            Log.e(TAG, "教师ID格式错误: " + currentTeacherId);
        }
    }

    private void loadAssignmentData() {
        if (currentCourse == null) {
            Toast.makeText(this, "无法加载作业：未找到课程信息", Toast.LENGTH_SHORT).show();
            return;
        }

        // 1. 获取 TeamAssignmentApi 实例
        TeamAssignmentApi api = RetrofitClient.getTeamAssignmentApi();

        // 需要更改此出将逻辑变成获取作业id的逻辑
        Call<List<TeamAssignment>> call = api.getTeamAssignmentsByAssignment(currentCourse.getCourseId());

        call.enqueue(new Callback<List<TeamAssignment>>() {
            @Override
            public void onResponse(Call<List<TeamAssignment>> call, Response<List<TeamAssignment>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    List<TeamAssignment> assignments = response.body();

                    if (!assignments.isEmpty()) {
                        // 转换数据格式并更新UI
                        List<AssignmentDisplay> displayList = convertToDisplayList(assignments);
                        adapter.updateData(displayList);

                        Log.d(TAG, "成功获取作业数据，数量: " + assignments.size());
                        Toast.makeText(AssignmentListActivity.this, "加载了 " + assignments.size() + " 个作业", Toast.LENGTH_SHORT).show();
                    } else {
                        // 没有作业数据
                        adapter.updateData(new ArrayList<>());
                        Toast.makeText(AssignmentListActivity.this, "该课程暂无作业", Toast.LENGTH_SHORT).show();
                        Log.w(TAG, "该课程暂无作业数据");
                    }

                } else if (response.code() == 404) {
                    // 404 表示未找到作业
                    adapter.updateData(new ArrayList<>());
                    Toast.makeText(AssignmentListActivity.this, "该课程暂无作业", Toast.LENGTH_SHORT).show();
                } else {
                    // 其他 API 错误
                    String errorMsg = "获取作业数据失败: 错误码 " + response.code();
                    Toast.makeText(AssignmentListActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                    Log.w(TAG, "获取作业数据失败，状态码: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<List<TeamAssignment>> call, Throwable t) {
                // 网络或连接错误
                Toast.makeText(AssignmentListActivity.this, "获取作业数据失败：" + t.getMessage(), Toast.LENGTH_LONG).show();
                Log.e(TAG, "获取作业数据网络错误: " + t.getMessage());
            }
        });
    }

    private List<AssignmentDisplay> convertToDisplayList(List<TeamAssignment> assignments) {
        List<AssignmentDisplay> displayList = new ArrayList<>();

        for (TeamAssignment assignment : assignments) {
            AssignmentDisplay display = new AssignmentDisplay();

            // 复制基本字段
            display.setId(assignment.getId());
            display.setTeamId(assignment.getTeamId());
            display.setSubmittedBy(assignment.getSubmittedBy());
            display.setScore(assignment.getScore() != null ? assignment.getScore().doubleValue() : 0.0);
//            display.setSubmittedAt(assignment.getSubmittedAt());
//            display.setCreatedAt(assignment.getCreatedAt());
            display.setIsExcellent(assignment.getIsExcellent());
            display.setCourseId(assignment.getAssignmentId());

            // 设置显示字段
            display.setTeamName("第" + assignment.getTeamId() + "组");
            display.setStudentName("学生" + assignment.getSubmittedBy());
            display.setCourseName(currentCourse != null ? currentCourse.getCourseName() : "未知课程");
            display.setCourseDescription(currentCourse != null ? currentCourse.getDescription() : "");

            displayList.add(display);
        }

        return displayList;
    }

    private void updateCourseUI(Course course) {
        if (course != null) {
            //tvCourseTitle.setText(course.getCourseName());
            tvCourseDescription.setText(course.getDescription());

            // 更新主标题为课程名称
//            tvMainTitle.setText(course.getCourseName());

            Log.i(TAG, "更新课程UI: " + course.getCourseName());
        }
    }

    private void showDefaultCourseInfo() {
        tvCourseTitle.setText("课程需求");
        tvCourseDescription.setText("python");
        tvMainTitle.setText("项目实践");

        Log.w(TAG, "使用默认课程信息");
    }

    private void onAssignmentItemClick(AssignmentDisplay assignment) {
        // 处理作业项点击事件，跳转到评分页面
        Intent intent = new Intent(this, BottomMenuActivity.class);
        intent.putExtra("assignmentId", assignment.getId());
        intent.putExtra("teamName", assignment.getDisplayName());
        intent.putExtra("currentScore", assignment.getScore());
        intent.putExtra("courseId", currentCourse != null ? currentCourse.getCourseId() : "default");

        Log.d(TAG, "点击作业项: " + assignment.getDisplayName() + ", 分数: " + assignment.getScore());
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            // 刷新作业数据
            loadAssignmentData();
            Toast.makeText(this, "评分已更新", Toast.LENGTH_SHORT).show();
            Log.i(TAG, "从评分页面返回，刷新作业数据");
        }
    }

    // 刷新数据方法，可以从其他页面调用
    public void refreshData() {
        loadCourseData();
    }
}